<template>
  <div class="my-tag">
    <input
      class="input"
      type="text"
      placeholder="输入标签"
      @blur="close"
      @keyup.enter="setEditFn"
      v-focus
      v-if="edit"
      v-model.trim="editTag"
    />
    <div v-else class="text" @dblclick="open">{{value}}</div>
  </div>
</template>

<script>
// 1. 双击文字可以显示出input框
// 2. 显示出input框时 需要聚焦  并且还原文字
// 3. 失去焦点时还原  点回车的时候修改文字
export default {
  // 通过v-model父传子的变量名叫value
  props: {
    value: String
  },
  data() {
    return {
      edit: false,
      editTag: ''
    }
  },
  methods:{
    open () {
      this.edit = true
      // 还原标签
      this.editTag = this.value
    },
    close() {
      this.edit = false
    },
    setEditFn() {
      this.edit = false
      // 健全
      if (this.editTag === '') {
        this.editTag= '暂无'
      }
      // 修改父组件传进来的value 需要子传父
      this.$emit('input', this.editTag)
    }
  },
  directives: {
    focus: {
      inserted(el) {
        el.focus()
      }
    }
  }
}
</script>

<style lang="less">
.open {
  cursor: pointer;
  .input {
    appearance: none;
    outline: none;
    border: 1px solid #ccc;
    width: 100px;
    height: 40px;
    box-sizing: border-box;
    padding: 10px;
    color: #666;
    &::placeholder {
      color: #666;
    }
  }
}

</style>
